package cn.myspringboot.common.controller;

import cn.myspringboot.anno.PreAuthorize;
import cn.myspringboot.utils.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Api("文件上传相关接口")
@RestController
@RequestMapping("/minio")
public class MinIoController {
    private static final String ACCESSKEY = "admin";   //用户名
    private static final String SECREKEY = "yuxiaoyuan"; //密码
    private static final String ADDRESS = "http://192.168.0.105:9000"; //访问端口号也是9090
    private static final String BUCKETNAME = "java241104";  //桶
    //上传文件

    @PreAuthorize(name = "上传文件",sn = "minio:upload",descs ="上传文件")
    @ApiOperation("上传文件")
    @PostMapping
    public R upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            String fileName = System.currentTimeMillis()+oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName)	//文件名
                .bucket(MinIoController.BUCKETNAME)  //存储目录名
                .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片
            String url = ADDRESS + "/" + BUCKETNAME + "/" + fileName;
            System.out.println(url);
            //执行上传
            minioClient.putObject(putObjectArgs);
            R oo = R.ok();
            oo.setData(url);
            return oo;

        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }

    //删除文件
    @PreAuthorize(name = "删除文件",sn = "minio:delete",descs ="删除文件")
    @ApiOperation("删除文件")
    @DeleteMapping("/{name}")
    public R delete(@PathVariable("name")String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            minioClient.removeObject(MinIoController.BUCKETNAME, name);
            return R.ok();
        } catch (Exception e) {
            return R.fail("删除失败");
        }
    }
}